var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var session = require('express-session');
var app = express();

// 导入并配置cors中间件 --(为了解决浏览器的跨域问题)
// 必须写在注册路由前面！！！
const cors = require('cors');
app.use(cors());
//captcha验证码的存储时间等
app.use(session({
  secret: 'keyboard cat', // 对session id 相关的cookie 进行签名
  resave: false,
  saveUninitialized: true, // 是否保存未初始化的会话
  cookie: {
    secure: false,
    maxAge: 1000 * 60 * 60 * 24
  },// 设置 session 的有效时间，单位毫秒},
}))
//定义接口路由
var indexRouter = require('./routes/index');
const expressJwt = require('express-jwt')
const secreatKey = 'coderwh'
// 去除登录和图片验证token
app.use(expressJwt({
  algorithms: ['HS256'],
  secret: secreatKey
}).unless({
  path: [/^\/api/, /^\/admin\/login/, /^\/images/]
}))

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
//托管静态文件
app.use(express.static('public'));


app.use(logger('dev'));
app.use(express.json()); //解析格式请求的数据
app.use(express.urlencoded({
  extended: false
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});
// app.listen(3000); 
module.exports = app;